package com.earstep
{
	import com.earstep.controller.VictopController;
	import com.earstep.proxy.LoginProxy;
	import com.earstep.view.LoginView;
	import com.earstep.view.LoginViewMediator;
	import com.earstep.view.MainViewMediator;
	import com.earstep.view.PopupWindowMediator;
	import com.erastep.event.CommonEvent;
	import com.erastep.util.CommonConstants;
	import com.erastep.util.LogUtil;
	import com.erastep.util.StringUtil;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import mx.containers.ViewStack;
	import mx.formatters.DateFormatter;
	
	import spark.components.Application;

	/**
	 * @depart 宁波维涛
	 * @author Jarvis 
	 * @E-mail: shaomj@victopsoft.com
	 * @version 1.0.1 
	 * 创建时间：2011-10-9 下午03:56:20 * 
	 */
	public class LoadBaseConfigController
	{
		public function LoadBaseConfigController()
		{
			
		}
		
		public static const CONFIG_URL:String = "assets/xml/config.xml";
		
		private var baseFrame:Object = {BASE_FRAME:"基础框架加载完成...",BASE_COMPONENT:"公用组件加载完成...",BASE_DATALINK:"数据引用加载完成...",BASE_DATACHANNEL:"数据通道加载完成..."};
		
		private var urlLoader:URLLoader;
		
		private var loader:Loader;
		
		private var context:LoaderContext;
		
		private var serverURL:String;
		
		private var loadIndex:int = 0;
		
		private var xmlList:XMLList;
		
		private var view:Application;
		
		private var start:Date,end:Date;
		
		private var vc:VictopController;
		
		private var login:LoginView;
		
		private var preLoadArrays:Array;
		
		private var defaultUser:Object;
		
		public function init(vt:Application):void{
			start = new Date();
			view = vt;
			urlLoader =new URLLoader();
			urlLoader.addEventListener(Event.COMPLETE, xmlLoadComplete);
			urlLoader.load(new URLRequest(CONFIG_URL));
			preLoadArrays = new Array(); 
			vc = new VictopController();
			
			//启动登陆界面
			login = new LoginView();
			login.id = "loginView";
			//login.logo_url.visible = false;
			(view["mainView"] as ViewStack).addChild(login);
			vc.registerMediator(new LoginViewMediator(login));
			view.focusManager.setFocus(login.user);	
			
			//调用js方法以及提供给js接口
			//ExternalInterface.call("getFoucus");
			//ExternalInterface.addCallback("sendNotification",sendNotification);
			
		}
		
		public function sendNotification(messageName:String,body:Object):void{
			var df:DateFormatter = new DateFormatter();
			df.formatString =  "YYYY-MM-DD JJ:NN:SS";
			LogUtil.print("结束访问:"+df.format(new Date()));
			vc.sendNotification(messageName,body,CommonConstants.JS_CALL_FLEX_TYPE);
		}
		/**
		 * 预加载模块
		 * */
		public function preLoadModule(rid:String,cls:Class,systemId:int,formId:int):void{
			preLoadArrays.push({rid:rid,cls:cls,systemId:systemId,formId:formId});
			preLoadArrays[rid] = {rid:rid,cls:cls,systemId:systemId,formId:formId};
		}
		/**
		 * config.xml load complete
		 * */
		private function xmlLoadComplete(e:Event):void{
			//start register datachannel
			var xml:XML=XML(urlLoader.data);
			LogUtil.print("基础配置文件信息:"+xml);
			var app:String  = StringUtil.trim(xml.server.@application);
			var url:String = StringUtil.trim(xml.server.@url);
			if(StringUtil.trim(url) == ""){
				this.serverURL = wrapUrl()+"/"+app;//
			}else{
				this.serverURL = url +"/"+ app;
			}
			var lc:LoginProxy = new LoginProxy();
			login.user.enabled = true;
			login.pass.enabled = true;
			var keepLive:Object = new Object();
			keepLive.interval = xml.keeplive.@interval;
			keepLive.maxtime = xml.keeplive.@maxtime;
			vc.company = String(xml.logo.@name);
			var username:String = xml.defaultuser.@username;
			var password:String = xml.defaultuser.@password;
			defaultUser = {username:username,password:password};
			LogUtil.print("服务器路径.."+this.serverURL);
			//this.serverURL = "http://127.0.0.1:8080/victop-web-flex";
			vc.host = this.serverURL;
			vc.registerProxy(lc);
			//var suc:SocketUtilController = new SocketUtilController();
			//vc.registerMediator(suc);
			xmlList = XMLList(xml.modules.module);
			startLoadFlexFrame();
		}
		
		
		private function startLoadFlexFrame():void{
			if(xmlList.length() > 0){
				var xml:XML = xmlList[loadIndex] as XML;
				loader=new Loader();
				context=new LoaderContext(false, ApplicationDomain.currentDomain);
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadFrameComplete);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void{
					trace("加载失败:"+baseFrame[xml.@id]);
				});
				loader.load(new URLRequest(xml.@url), context);
				//监听进度条					
				loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, handleProgress); 
			}
		}
		
		/**
		 * base frame swf load complete
		 * */
		private function loadFrameComplete(e:Event):void{
			trace("######## "+xmlList.length());
			if(loadIndex < xmlList.length()){
				var xml:XML = xmlList[loadIndex] as XML;
				loadIndex ++;
				if(loadIndex != xmlList.length()){
					trace("加载成功:"+baseFrame[xml.@id]);
					startLoadFlexFrame();
				}else{
					//all frame load complete
					LogUtil.print("all frame loaded success!");
					if(!vc.pluginList){
						vc.pluginList = new Array();
					}
				    var mainView:MainViewMediator = new MainViewMediator(view);
					vc.registerMediator(mainView);
					var popwindow:PopupWindowMediator = new PopupWindowMediator(view);
					vc.registerMediator(popwindow);
					/*for(var i:int = 0;i < xmlList.length();i++){
						xml = xmlList[i] as XML;
						if(xml.@type == CommonConstants.MODULE){
							var cls:Class = getDefinitionByName("com.victop."+xml.@id+".Main") as Class;
							// at here register module
							vc.registerModule(xml.@id,cls);
							//register module info
							var module:ModuleVO = new ModuleVO();
							module.resourceid = xml.@id;
							module.formid = xml.@systemId;
							module.systemid = xml.@formId;
							module.url = xml.@url;
							vc.pluginList[module.systemid+"#"+module.formid] = module;
							vc.pluginList.push(module);
						}
					}
				    //vc.registerTestModule(CommonConstants.HOMEPAGE,com.victop.homepage.Main,{systemId:"10",formId:"1"});
					vc.sendNotification(CommonConstants.HOMEPAGE,keepLive,null,CommonConstants.MODULE);*/
					if(preLoadArrays.length > 0){
						for each(var item:Object in preLoadArrays){
							vc.registerTestModule(item.rid,item.cls,{systemId:item.systemId,formId:item.formId});
						}
						for each(item in preLoadArrays){
							if(item.systemId == -1 && item.formId == -1){
								trace("================    "+item.rid);
								vc.sendNotification(item.rid,null,null,CommonConstants.MODULE);
								break;
							}
						}
					} 
					vc.preLoadHome = this.preLoadArrays;
					//-----------------------------------注册测试插件---------------------------------------
			
					//-----------------------------------结束注册插件---------------------------------------
					vc.init(view);
					LogUtil.print("Victop Flex Frame instance success!");
					end = new Date();
					LogUtil.print("系统初始化用时:"+(end.getTime()-start.getTime()));
					vc.locked = true;
					vc.retriveMediator(LoginViewMediator.NAME).callFunction("defaultLogin",defaultUser);
					
				}
			}
		}
		private function loadResourceHandler(e:CommonEvent):void{
			trace(e.params.bytesLoaded + "======" +e.params.bytesTotal);		
		}
		
		private function handleProgress(e:ProgressEvent):void{
			trace("=========== "+e.bytesTotal+" ========= "+e.bytesLoaded);
		}
		
		// temp method
		public  function wrapUrl():String
		{
			var urlFix:String;
			var result:String = "",url:String = "";
			if (! urlFix)
			{
				urlFix = ExternalInterface.call("function getURL(){return window.location.href;}");
			}
			if (urlFix &&(  (urlFix.substr(0,4)== "http") || (urlFix.substr(0,4)== "HTTP")) )
			{
				for (var i:int = 0;i<urlFix.length; i++)
				{
					if (urlFix.charAt(i) == "/" && urlFix.charAt(i-1) != "/" && urlFix.charAt(i+1) != "/")
					{
						urlFix = urlFix.substring(0,i);
						break;
					}
				}
				result = urlFix + url;
			}else{
				result = url;
			}
			return result;
		}
	}
}